/*
 *  Openmysee
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#pragma once

namespace gaov {
namespace chaos {

#include <Winsock2.h>
#include "NetParse.h"

		class TCPConn
		{
		public:
			bool InitNetwork();
			PSTREAM	InitData(UINT maxlen);
			int Send(PSTREAM s); // -1 : sock error;  1 : success
			PSTREAM Recv(PSTREAM s, UINT length);
			void Close(){ 
				if(sock!=INVALID_SOCKET){
					closesocket(sock); 
					sock = INVALID_SOCKET;
					WSACleanup();
				} 
			}

		protected:
			TCPConn() : sock(INVALID_SOCKET), m_bNetworkInited(false){}
			virtual ~TCPConn(){ 
				Close();
			}

		protected:
			bool m_bNetworkInited;

			SOCKET sock;
			STREAM in;
			STREAM out;
		};

		class TCPClient : public TCPConn
		{
		public:
			TCPClient(){};
			TCPClient(SOCKET s) { sock = s; };
			~TCPClient(){}

			int Connect(const char* sIP, USHORT port); // -2 : connection exists;  -1 : sock error
			// 0 : mem error;  1 : success
			bool SendEx(UINT8 msgType, UINT8 subMsgType, PBYTE data, UINT dataLen);
			bool SendEx2(UINT8 msgType, UINT8 subMsgType, PBYTE data1, UINT dataLen1, PBYTE data2, UINT dataLen2);
			bool RecvEx(UINT8& msgType, UINT8& subMsgType, PBYTE& data, UINT& dataLen, const bool bRecvData=true);
			bool RecvEx2(UINT8& msgType, UINT8& subMsgType, PBYTE& data1, UINT& dataLen1, PBYTE& data2, UINT& dataLen2, const bool bRecvData=true );

		private:
		};

		class TCPServer : public TCPConn
		{
		public:
			TCPServer(){};
			~TCPServer(){}

			bool	Listen(const char* sIP, USHORT port);
			SOCKET	Accept();

		private:
		};

	};
};